<template>
  <div class="car-payment-plan-wrapper">
    <a-modal popup-container=".page-container" width="90%" title="账单计划" @cancel="close" :visible="visible" unmount-on-close>
      <div class="payment-plan-wrapper">
        <a-alert>
          <template #icon> <icon-exclamation-circle /> </template>如需修改付款计划，请先保存页面信息，再前往车辆的<span class="link"
            >【费用信息】</span
          >页面，点击<span class="link">【修改费用】</span>进行调整。
        </a-alert>

        <div class="payment-plan-header">
          <div class="mr56" v-if="originDetail?.contractCarPurchaseEditVo?.purchaseNo.startsWith('GZ')">
            车辆费用单号: {{ originDetail.contractCarPurchaseEditVo.purchaseNo }}
          </div>
          <div class="mr56" v-if="originDetail?.contractCarPurchaseEditVo?.purchaseNo.startsWith('DC')">
            调车单号: {{ originDetail.contractCarPurchaseEditVo.purchaseNo }}
          </div>
          <div class="mr56">
            应{{ sourceTit }}总额：
            <span class="num">{{ recordAmount?.payableTotalAmount ?? '-' }}</span>
            <span class="ml-1">元</span>
          </div>
          <div class="mr56">
            已{{ sourceTit }}总额：
            <span class="num">{{ recordAmount?.paidTotalAmount ?? '-' }}</span>
            <span class="ml-1">元</span>
          </div>
          <div class="mr56">
            剩余应{{ sourceTit }}：
            <span class="num">{{ recordAmount?.unpaidTotalAmount ?? '-' }}</span>
            <span class="ml-1">元</span>
          </div>
          <div class="mr56">
            {{ recordAmount?.purchaseFeeType == 1 ? '车辆购置费总额' : '车辆借入总额' }}：
            <span class="num">{{ recordAmount?.purchaseTotalFee ?? 0 }}</span>
            <span class="ml-1">元</span>
          </div>
        </div>
        <a-table
          class="business-fee-table"
          :columns="columns"
          :scroll="{ x: 1200, y: '60vh' }"
          :data="tableData"
          :pagination="false"
          :bordered="false"
        >
          <template #payableNumStr="{ record }"> {{ recordAmount.feeCategoryName }}-{{ record?.payableNumStr }} </template>
          <template #payableTimeStr="{ record }">
            <template v-if="status == 'view'">{{ record.payableTimeStr }}</template>
            <template v-else>
              <i-date-picker v-model="record.payableTimeStr" />
            </template>
          </template>
          <template #payableAmount="{ record }">
            <template v-if="status == 'view'">{{ record.payableAmount }}</template>
            <template v-else>
              <i-input-number :min="0.01" v-model="record.payableAmount" />
            </template>
          </template>
          <template #billRemark="{ record }">
            <template v-if="status == 'view'">{{ record.billRemark || '-' }}</template>
            <template v-else>
              <i-input v-model="record.billRemark" :max-length="10" />
            </template>
          </template>
          <template #paymentAmount="{ record }">
            {{ record.paymentAmount || '-' }}
          </template>
          <template #payableStatusName="{ record }">
            {{ record.payableStatusName || '-' }}
          </template>
          <template #paymentTime="{ record }">
            {{ record.paymentTime || '-' }}
          </template>
          <template #operate="{ record, rowIndex }">
            <div class="table-operator">
              <div class="operate-item operate-minus" @click="delPaymentPlanFn(rowIndex, record)" v-if="showDelFn(record)">
                <icon-minus-circle />删除本期
              </div>
              <div class="operate-item operate-plus" @click="addPaymentPlanFn(record)" v-if="showAddFn(record)">
                <icon-plus-circle />添加新期数
              </div>
            </div>
          </template>
        </a-table>
      </div>
      <template #footer>
        <a-button @click="close">关闭</a-button>
        <a-button type="primary" v-if="status == 'edit'" :loading="submitLoading" @click="handleOk">确认</a-button>
      </template>
    </a-modal>
    <!-- 编辑付款计划，二次确认 -->
    <car-payment-plan-confirm-modal ref="carPaymentPlanConfirmModalRef" @ok="saveApi" />
  </div>
</template>

<script setup name="CarPaymentPlanModal">
  import { ref, computed, inject } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { editPurchaseBillInfo } from '@/api/asset/car.js'
  import { Notification } from '@arco-design/web-vue'
  import carPaymentPlanConfirmModal from './car-payment-plan-confirm-modal.vue'
  const originDetail = inject('originDetail')
  const visible = ref(false)
  const status = ref('view')
  const tableData = ref([])
  const emit = defineEmits(['success'])
  const columns = ref([])
  const updateColumns = () => {
    const cols = [
      { title: '期数', dataIndex: 'payableNumStr', slotName: 'payableNumStr' },
      { title: '应结日期', dataIndex: 'payableTimeStr', slotName: 'payableTimeStr' },
      { title: `应${sourceTit}金额(元)`, dataIndex: 'payableAmount', slotName: 'payableAmount' },
      { title: `实${sourceTit}金额(元)`, dataIndex: 'paymentAmount', slotName: 'paymentAmount' },
      { title: '费用状态', dataIndex: 'payableStatusName', slotName: 'payableStatusName' },
      { title: `实际${sourceTit}款时间`, dataIndex: 'paymentTime', slotName: 'paymentTime' },
      { title: '备注', dataIndex: 'billRemark', slotName: 'billRemark' },
      {
        title: '操作',
        dataIndex: 'operate',
        slotName: 'operate',
        fixed: 'right',
        width: 140,
      },
    ]

    if (status.value === 'view') {
      cols.pop() // 移除操作列
    }
    columns.value = cols
  }
  // 是否显示删除
  const showDelFn = (record) => {
    // 获取最大的期数（首期为-1 尾期为-2）
    let max = 0
    tableData.value.forEach((item) => {
      if (item.payableNum >= max) {
        max = item.payableNum
      }
    })
    if (tableData.value.length > 1) {
      if (record.payableNum == max) {
        return true
      }
    }
    if (record.payableNum == -2 || record.payableNum == -1) {
      return true
    }
    return false
  }
  const showAddFn = (record) => {
    let max = -1
    tableData.value.forEach((item) => {
      if (item.payableNum >= max) {
        max = item.payableNum
      }
    })
    if (record.payableNum == max) {
      return true
    }
    return false
  }
  // 删除分期
  const delPaymentPlanFn = (index, record) => {
    if (record.payableNum == 1) {
      Message.warning(`请至少保留一期`)
    } else {
      tableData.value.splice(index, 1)
    }
  }
  // 添加分期
  const addPaymentPlanFn = (record) => {
    console.log(record)
    // 应付款日
    let payableTimeStr = record.payableTimeStr
    // 付款金额
    let payableAmount = record.payableAmount
    if (!payableTimeStr || !payableAmount) {
      let payableNumStr = record.payableNumStr
      let noInput = ''
      if (!payableTimeStr && !payableAmount) {
        noInput = `应${sourceTit}款日和应${sourceTit}金额`
      } else {
        noInput = !payableTimeStr ? `应${sourceTit}款日` : `应${sourceTit}金额`
      }
      Message.warning(`请录入${payableNumStr}${noInput}`)
      return
    }
    let tableVal = tableData.value
    // 由于添加新分期在 最后一期上（不是尾期），所以新分期的 payableNum 值为当前分期 + 1
    let payableNum = record.payableNum + 1
    let payableNumStr = `第${payableNum}期`
    // 存在尾期
    let newTableItem = {
      payableNum,
      payableNumStr,
      settlementStatusStr: '待结算',
      contractId: prevContractId,
    }
    // 存在尾期
    if (tableVal.some((item) => item.payableNum == -2)) {
      tableData.value.splice(payableNum, 0, newTableItem)
    } else {
      tableData.value.push(newTableItem)
    }
  }
  // 获取分期数
  const getInstalmentNum = (data) => {
    return data.filter((item) => item.payableNum != -1 && item.payableNum != -2).length
  }
  const carPaymentPlanConfirmModalRef = ref()
  const handleOk = () => {
    // 判断必填项是否书写 start
    let nowData = tableData.value
    let hasNoInput = nowData.some((item) => {
      let flag = !item.payableTimeStr || item.payableAmount == '' || item.payableAmount == undefined
      return flag
    })
    if (hasNoInput) {
      return Message.warning('请填写必填项')
    }
    // 判断必填项是否书写 end
    // 判断日期是否小于首期付款日
    // 从第2期开始判断，第1期时间不做限制，可以比首期时间早
    for (let i = 1; i < nowData.length; i++) {
      let nowItem = nowData[i]
      let payableNum = nowItem.payableNum
      if (payableNum == 1) {
        continue
      }
      let prevItem = nowData[i - 1]
      let nowTime = nowItem.payableTimeStr
      let nowTStamp = new Date(nowTime).getTime()
      let prevTime = prevItem.payableTimeStr
      let prevTStamp = new Date(prevTime).getTime()
      if (nowTStamp < prevTStamp) {
        return Message.warning(`${nowItem.payableNumStr}应${sourceTit}款日需大于等于上一期的应${sourceTit}款日`)
      }
    }
    // 判断日期是否后面日期超过前面日期
    let prevData = prevRecordData
    // 变化的数量
    let changedNumber = 0
    // 1 首款/尾款是否有变化
    // 首款
    let initialAmount = {
      change: false,
    }
    if (prevData.some((item) => item.payableNum == -1)) {
      initialAmount.prev = prevData[0].payableAmount
      if (nowData.some((item) => item.payableNum == -1)) {
        initialAmount.now = nowData[0].payableAmount
      } else {
        initialAmount.now = '删除'
      }
      let changedAmount = initialAmount.prev != initialAmount.now
      if (changedAmount) {
        initialAmount.change = changedAmount
        changedNumber += 1
      }
    }
    // 尾款
    let balanceAmount = {
      change: false,
    }
    if (prevData.some((item) => item.payableNum == -2)) {
      balanceAmount.prev = prevData[prevData.length - 1].payableAmount
      if (nowData.some((item) => item.payableNum == -2)) {
        balanceAmount.now = nowData[nowData.length - 1].payableAmount
      } else {
        balanceAmount.now = '删除'
      }
      let changedBalanceAmount = balanceAmount.prev != balanceAmount.now
      if (changedBalanceAmount) {
        balanceAmount.change = changedBalanceAmount
        changedNumber += 1
      }
    }
    // 2 账单总金额同车辆详情中设置的合同总金额是否有出入
    let totalAmount = {
      change: false,
      prev: 0,
      now: 0,
    }
    let prevSum = 0
    prevData.forEach((item) => {
      prevSum += item.payableAmount
    })
    let nowSum = 0
    nowData.forEach((item) => {
      nowSum += item.payableAmount
    })
    totalAmount.prev = prevSum
    totalAmount.now = nowSum
    let changedTotalAmount = prevSum != nowSum
    if (changedTotalAmount) {
      totalAmount.change = changedTotalAmount
      changedNumber += 1
    }
    // 3 期数是否有变化
    let prevInstalmentNum = getInstalmentNum(prevData)
    let nowInstalmentNum = getInstalmentNum(nowData)
    let lnstalmentNum = {
      change: false,
      prev: prevInstalmentNum,
      now: nowInstalmentNum,
    }
    let changedInstalmentNum = prevInstalmentNum != nowInstalmentNum
    if (changedInstalmentNum) {
      lnstalmentNum.change = true
      changedNumber += 1
    }
    if (changedNumber > 0) {
      let confirmData = {
        initialAmount,
        balanceAmount,
        totalAmount,
        lnstalmentNum,
      }
      carPaymentPlanConfirmModalRef.value.open(confirmData)
    } else {
      saveApi()
    }
  }
  // 保存接口
  const submitLoading = ref(false)
  const saveApi = () => {
    let list = tableData.value
    let tempList = list.map((item) => {
      let payableTime = item.payableTimeStr.replace(/\//g, '-') + ' 00:00:00'
      return {
        id: item.id,
        payableNum: item.payableNum,
        payableTime: payableTime,
        payableAmount: item.payableAmount,
        billRemark: item.billRemark,
        contractId: item.contractId,
      }
    })
    submitLoading.value = true
    editPurchaseBillInfo(tempList)
      .then(() => {
        submitLoading.value = false
        Notification.success({
          content: '保存成功',
          closable: true,
          duration: 10000,
        })
        emit('success')
        close()
      })
      .catch(() => {
        submitLoading.value = false
      })
  }
  // 存储 prevRecordData，用于点击确认的时候判断是否变化
  let prevRecordData = null
  let prevContractId = null
  let recordAmount = null
  let sourceTit = '付'
  const open = (data, contractId) => {
    prevContractId = contractId || null
    prevRecordData = JSON.parse(JSON.stringify(data)).payableList
    visible.value = true
    tableData.value = data.payableList
    status.value = 'view'
    recordAmount = data
    sourceTit = data.source == 2 ? '收' : '付'
    updateColumns()
  }
  const close = () => {
    visible.value = false
  }
  defineExpose({
    open,
    close,
  })
</script>

<style lang="less" scoped>
  .table-operator {
    .operate-item {
      display: inline-block;
      font-size: 14px;
      padding: 0 4px;
      cursor: pointer;
    }
    .operate-minus {
      color: #f53f3f;
    }
    .operate-plus {
      color: #165dff;
    }
  }
  .business-fee-table {
    width: 100%;
  }
  .operate-list {
    padding-bottom: 10px;
  }
  .payment-plan-header {
    display: flex;
    align-items: center;
    margin: 16px 0;
  }
  .link {
    color: #3072f6;
  }
  .num {
    color: #1890ff;
  }
  .mr56 {
    margin-right: 56px;
  }
</style>
